//
//  PhotoRestorationViewController.swift
//  ScarnKing
//
//  Created by ninebot on 2025/7/22.
//

import UIKit
import AVFoundation
import SVProgressHUD

class PhotoRestorationViewController: UIViewController {
    
    // MARK: - UI Components
    private let cameraPreviewView = UIView()
    private let overlayView = UIView()
    private let scanFrameView = UIView()
    private let cornerViews = [UIView(), UIView(), UIView(), UIView()]
    
    private let headerView = UIView()
    private let titleLabel = UILabel()
    private let backButton = UIButton(type: .system)
    private let flashButton = UIButton(type: .system)
    
    private let bottomView = UIView()
    private let instructionLabel = UILabel()
    private let captureButton = UIButton(type: .system)
    private let albumButton = UIButton(type: .system)
    
    private let resultView = UIView()
    private let originalImageView = UIImageView()
    private let restoredImageView = UIImageView()
    private let comparisonView = UIView()
    private let resultActionsView = UIView()
    private let saveButton = UIButton(type: .system)
    private let shareButton = UIButton(type: .system)
    private let retakeButton = UIButton(type: .system)
    private let restoreButton = UIButton(type: .system)
    
    // MARK: - Camera Properties
    private var captureSession: AVCaptureSession!
    private var stillImageOutput: AVCapturePhotoOutput!
    private var previewLayer: AVCaptureVideoPreviewLayer!
    private var isFlashOn = false
    
    // MARK: - State
    private var isScanning = false
    private var originalImage: UIImage?
    private var restoredImage: UIImage?
    private var isRestoring = false
    
    // MARK: - Network
    private let networkManager = SKAFNetWork()
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupConstraints()
        setupCamera()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 隐藏导航栏和底部导航栏
        navigationController?.setNavigationBarHidden(true, animated: false)
        navigationController?.tabBarController?.tabBar.isHidden = true
        
        // 自动开始扫描
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
            self?.startScanning()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 显示导航栏和底部导航栏
        navigationController?.setNavigationBarHidden(false, animated: false)
        navigationController?.tabBarController?.tabBar.isHidden = false
        captureSession?.stopRunning()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // 更新预览层frame
        previewLayer?.frame = cameraPreviewView.bounds
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        let isDark = ThemeManager.shared.isDarkMode
        view.backgroundColor = .black
        
        setupHeaderView()
        setupCameraPreview()
        setupBottomView()
        setupResultView()
        
        // 监听主题变化
        NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeDidChange, object: nil)
    }
    
    private func setupHeaderView() {
        let isDark = ThemeManager.shared.isDarkMode
        
        titleLabel.text = "老照片修复"
        titleLabel.font = UIFont.boldSystemFont(ofSize: 20)
        titleLabel.textColor = .white
        titleLabel.textAlignment = .center
        
        backButton.setImage(UIImage(systemName: "xmark.circle.fill"), for: .normal)
        backButton.tintColor = .white
        backButton.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        backButton.layer.cornerRadius = 20
        backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        
        flashButton.setImage(UIImage(systemName: "bolt.slash.fill"), for: .normal)
        flashButton.tintColor = .white
        flashButton.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        flashButton.layer.cornerRadius = 20
        flashButton.addTarget(self, action: #selector(flashButtonTapped), for: .touchUpInside)
        
        headerView.backgroundColor = .clear
    }
    
    private func setupCameraPreview() {
        // 相机预览视图
        cameraPreviewView.backgroundColor = .black
        
        // 覆盖层
        overlayView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        // 扫描框
        scanFrameView.backgroundColor = .clear
        scanFrameView.layer.borderWidth = 2
        scanFrameView.layer.borderColor = UIColor.systemPurple.cgColor
        scanFrameView.layer.cornerRadius = 12
        
        // 四个角落的指示器
        for cornerView in cornerViews {
            cornerView.backgroundColor = UIColor.systemPurple
            cornerView.layer.cornerRadius = 4
        }
    }
    
    private func setupBottomView() {
        let isDark = ThemeManager.shared.isDarkMode
        
        instructionLabel.text = "将老照片放在紫色框内，点击拍照按钮进行修复"
        instructionLabel.font = UIFont.systemFont(ofSize: 16)
        instructionLabel.textColor = .white
        instructionLabel.textAlignment = .center
        instructionLabel.numberOfLines = 0
        
        captureButton.setImage(UIImage(systemName: "camera.circle.fill"), for: .normal)
        captureButton.tintColor = .white
        captureButton.backgroundColor = UIColor.systemPurple
        captureButton.layer.cornerRadius = 35
        captureButton.addTarget(self, action: #selector(captureButtonTapped), for: .touchUpInside)
        
        albumButton.setImage(UIImage(systemName: "photo.on.rectangle"), for: .normal)
        albumButton.tintColor = .white
        albumButton.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        albumButton.layer.cornerRadius = 25
        albumButton.addTarget(self, action: #selector(albumButtonTapped), for: .touchUpInside)
        
        bottomView.backgroundColor = .clear
    }
    
    private func setupResultView() {
        let isDark = ThemeManager.shared.isDarkMode
        
        // 原图显示
        originalImageView.contentMode = .scaleAspectFit
        originalImageView.backgroundColor = .black
        originalImageView.layer.cornerRadius = 12
        originalImageView.clipsToBounds = true
        originalImageView.isHidden = true
        
        // 修复后图片显示
        restoredImageView.contentMode = .scaleAspectFit
        restoredImageView.backgroundColor = .black
        restoredImageView.layer.cornerRadius = 12
        restoredImageView.clipsToBounds = true
        restoredImageView.isHidden = true
        
        // 对比视图
        comparisonView.backgroundColor = .clear
        comparisonView.isHidden = true
        
        // 操作按钮
        saveButton.setTitle("保存", for: .normal)
        saveButton.setTitleColor(.white, for: .normal)
        saveButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        saveButton.backgroundColor = UIColor.systemBlue
        saveButton.layer.cornerRadius = 8
        saveButton.addTarget(self, action: #selector(saveButtonTapped), for: .touchUpInside)
        
        shareButton.setTitle("分享", for: .normal)
        shareButton.setTitleColor(.white, for: .normal)
        shareButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        shareButton.backgroundColor = UIColor.systemGreen
        shareButton.layer.cornerRadius = 8
        shareButton.addTarget(self, action: #selector(shareButtonTapped), for: .touchUpInside)
        
        restoreButton.setTitle("开始修复", for: .normal)
        restoreButton.setTitleColor(.white, for: .normal)
        restoreButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        restoreButton.backgroundColor = UIColor.systemPurple
        restoreButton.layer.cornerRadius = 8
        restoreButton.addTarget(self, action: #selector(restoreButtonTapped), for: .touchUpInside)
        
        retakeButton.setTitle("重拍", for: .normal)
        retakeButton.setTitleColor(.white, for: .normal)
        retakeButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        retakeButton.backgroundColor = UIColor.systemRed
        retakeButton.layer.cornerRadius = 8
        retakeButton.addTarget(self, action: #selector(retakeButtonTapped), for: .touchUpInside)
        
        resultView.backgroundColor = .clear
        resultView.isHidden = true
    }
    
    private func setupConstraints() {
        view.addSubview(cameraPreviewView)
        view.addSubview(overlayView)
        view.addSubview(scanFrameView)
        view.addSubview(headerView)
        view.addSubview(bottomView)
        view.addSubview(resultView)
        
        headerView.addSubview(titleLabel)
        headerView.addSubview(backButton)
        headerView.addSubview(flashButton)
        
        bottomView.addSubview(instructionLabel)
        bottomView.addSubview(captureButton)
        bottomView.addSubview(albumButton)
        
        resultView.addSubview(originalImageView)
        resultView.addSubview(restoredImageView)
        resultView.addSubview(comparisonView)
        resultView.addSubview(resultActionsView)
        resultActionsView.addSubview(saveButton)
        resultActionsView.addSubview(shareButton)
        resultActionsView.addSubview(restoreButton)
        resultActionsView.addSubview(retakeButton)
        
        for cornerView in cornerViews {
            scanFrameView.addSubview(cornerView)
        }
        
        // 设置约束
        cameraPreviewView.translatesAutoresizingMaskIntoConstraints = false
        overlayView.translatesAutoresizingMaskIntoConstraints = false
        scanFrameView.translatesAutoresizingMaskIntoConstraints = false
        headerView.translatesAutoresizingMaskIntoConstraints = false
        bottomView.translatesAutoresizingMaskIntoConstraints = false
        resultView.translatesAutoresizingMaskIntoConstraints = false
        
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        backButton.translatesAutoresizingMaskIntoConstraints = false
        flashButton.translatesAutoresizingMaskIntoConstraints = false
        
        instructionLabel.translatesAutoresizingMaskIntoConstraints = false
        captureButton.translatesAutoresizingMaskIntoConstraints = false
        albumButton.translatesAutoresizingMaskIntoConstraints = false
        
        originalImageView.translatesAutoresizingMaskIntoConstraints = false
        restoredImageView.translatesAutoresizingMaskIntoConstraints = false
        comparisonView.translatesAutoresizingMaskIntoConstraints = false
        resultActionsView.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        shareButton.translatesAutoresizingMaskIntoConstraints = false
        restoreButton.translatesAutoresizingMaskIntoConstraints = false
        retakeButton.translatesAutoresizingMaskIntoConstraints = false
        
        for cornerView in cornerViews {
            cornerView.translatesAutoresizingMaskIntoConstraints = false
        }
        
        NSLayoutConstraint.activate([
            // Camera Preview
            cameraPreviewView.topAnchor.constraint(equalTo: view.topAnchor),
            cameraPreviewView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            cameraPreviewView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            cameraPreviewView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            
            // Overlay
            overlayView.topAnchor.constraint(equalTo: view.topAnchor),
            overlayView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            overlayView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            overlayView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            
            // Header
            headerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            headerView.heightAnchor.constraint(equalToConstant: 44),
            
            backButton.leadingAnchor.constraint(equalTo: headerView.leadingAnchor),
            backButton.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            backButton.widthAnchor.constraint(equalToConstant: 40),
            backButton.heightAnchor.constraint(equalToConstant: 40),
            
            titleLabel.centerXAnchor.constraint(equalTo: headerView.centerXAnchor),
            titleLabel.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            
            flashButton.trailingAnchor.constraint(equalTo: headerView.trailingAnchor),
            flashButton.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            flashButton.widthAnchor.constraint(equalToConstant: 40),
            flashButton.heightAnchor.constraint(equalToConstant: 40),
            
            // Scan Frame
            scanFrameView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            scanFrameView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            scanFrameView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8),
            scanFrameView.heightAnchor.constraint(equalTo: scanFrameView.widthAnchor, multiplier: 1.4),
            
            // Corner Views
            cornerViews[0].topAnchor.constraint(equalTo: scanFrameView.topAnchor, constant: -2),
            cornerViews[0].leadingAnchor.constraint(equalTo: scanFrameView.leadingAnchor, constant: -2),
            cornerViews[0].widthAnchor.constraint(equalToConstant: 20),
            cornerViews[0].heightAnchor.constraint(equalToConstant: 4),
            
            cornerViews[1].topAnchor.constraint(equalTo: scanFrameView.topAnchor, constant: -2),
            cornerViews[1].trailingAnchor.constraint(equalTo: scanFrameView.trailingAnchor, constant: 2),
            cornerViews[1].widthAnchor.constraint(equalToConstant: 4),
            cornerViews[1].heightAnchor.constraint(equalToConstant: 20),
            
            cornerViews[2].bottomAnchor.constraint(equalTo: scanFrameView.bottomAnchor, constant: 2),
            cornerViews[2].leadingAnchor.constraint(equalTo: scanFrameView.leadingAnchor, constant: -2),
            cornerViews[2].widthAnchor.constraint(equalToConstant: 20),
            cornerViews[2].heightAnchor.constraint(equalToConstant: 4),
            
            cornerViews[3].bottomAnchor.constraint(equalTo: scanFrameView.bottomAnchor, constant: 2),
            cornerViews[3].trailingAnchor.constraint(equalTo: scanFrameView.trailingAnchor, constant: 2),
            cornerViews[3].widthAnchor.constraint(equalToConstant: 4),
            cornerViews[3].heightAnchor.constraint(equalToConstant: 20),
            
            // Bottom View
            bottomView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            bottomView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            bottomView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
            bottomView.heightAnchor.constraint(equalToConstant: 120),
            
            instructionLabel.topAnchor.constraint(equalTo: bottomView.topAnchor),
            instructionLabel.leadingAnchor.constraint(equalTo: bottomView.leadingAnchor),
            instructionLabel.trailingAnchor.constraint(equalTo: bottomView.trailingAnchor),
            
            captureButton.centerXAnchor.constraint(equalTo: bottomView.centerXAnchor),
            captureButton.bottomAnchor.constraint(equalTo: bottomView.bottomAnchor),
            captureButton.widthAnchor.constraint(equalToConstant: 70),
            captureButton.heightAnchor.constraint(equalToConstant: 70),
            
            albumButton.centerYAnchor.constraint(equalTo: captureButton.centerYAnchor),
            albumButton.trailingAnchor.constraint(equalTo: bottomView.trailingAnchor),
            albumButton.widthAnchor.constraint(equalToConstant: 50),
            albumButton.heightAnchor.constraint(equalToConstant: 50),
            
            // Result View
            resultView.topAnchor.constraint(equalTo: view.topAnchor),
            resultView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            resultView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            resultView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            
            originalImageView.topAnchor.constraint(equalTo: resultView.safeAreaLayoutGuide.topAnchor, constant: 80),
            originalImageView.leadingAnchor.constraint(equalTo: resultView.leadingAnchor, constant: 20),
            originalImageView.trailingAnchor.constraint(equalTo: resultView.trailingAnchor, constant: -20),
            originalImageView.heightAnchor.constraint(equalTo: originalImageView.widthAnchor, multiplier: 0.8),
            
            restoredImageView.topAnchor.constraint(equalTo: originalImageView.bottomAnchor, constant: 20),
            restoredImageView.leadingAnchor.constraint(equalTo: resultView.leadingAnchor, constant: 20),
            restoredImageView.trailingAnchor.constraint(equalTo: resultView.trailingAnchor, constant: -20),
            restoredImageView.heightAnchor.constraint(equalTo: restoredImageView.widthAnchor, multiplier: 0.8),
            
            resultActionsView.leadingAnchor.constraint(equalTo: resultView.leadingAnchor, constant: 20),
            resultActionsView.trailingAnchor.constraint(equalTo: resultView.trailingAnchor, constant: -20),
            resultActionsView.bottomAnchor.constraint(equalTo: resultView.safeAreaLayoutGuide.bottomAnchor, constant: -20),
            resultActionsView.heightAnchor.constraint(equalToConstant: 50),
            
            saveButton.leadingAnchor.constraint(equalTo: resultActionsView.leadingAnchor),
            saveButton.topAnchor.constraint(equalTo: resultActionsView.topAnchor),
            saveButton.bottomAnchor.constraint(equalTo: resultActionsView.bottomAnchor),
            saveButton.widthAnchor.constraint(equalTo: resultActionsView.widthAnchor, multiplier: 0.22),
            
            shareButton.leadingAnchor.constraint(equalTo: saveButton.trailingAnchor, constant: 8),
            shareButton.topAnchor.constraint(equalTo: resultActionsView.topAnchor),
            shareButton.bottomAnchor.constraint(equalTo: resultActionsView.bottomAnchor),
            shareButton.widthAnchor.constraint(equalTo: resultActionsView.widthAnchor, multiplier: 0.22),
            
            restoreButton.leadingAnchor.constraint(equalTo: shareButton.trailingAnchor, constant: 8),
            restoreButton.topAnchor.constraint(equalTo: resultActionsView.topAnchor),
            restoreButton.bottomAnchor.constraint(equalTo: resultActionsView.bottomAnchor),
            restoreButton.widthAnchor.constraint(equalTo: resultActionsView.widthAnchor, multiplier: 0.22),
            
            retakeButton.leadingAnchor.constraint(equalTo: restoreButton.trailingAnchor, constant: 8),
            retakeButton.topAnchor.constraint(equalTo: resultActionsView.topAnchor),
            retakeButton.bottomAnchor.constraint(equalTo: resultActionsView.bottomAnchor),
            retakeButton.widthAnchor.constraint(equalTo: resultActionsView.widthAnchor, multiplier: 0.22)
        ])
    }
    
    // MARK: - Camera Setup
    private func setupCamera() {
        captureSession = AVCaptureSession()
        captureSession.sessionPreset = .photo
        
        guard let backCamera = AVCaptureDevice.default(for: .video) else {
            showAlert(title: "错误", message: "无法访问相机")
            return
        }
        
        do {
            let input = try AVCaptureDeviceInput(device: backCamera)
            stillImageOutput = AVCapturePhotoOutput()
            
            if captureSession.canAddInput(input) && captureSession.canAddOutput(stillImageOutput) {
                captureSession.addInput(input)
                captureSession.addOutput(stillImageOutput)
                setupLivePreview()
            }
        } catch {
            showAlert(title: "错误", message: "相机配置失败")
        }
    }
    
    private func setupLivePreview() {
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        previewLayer.videoGravity = .resizeAspectFill
        previewLayer.connection?.videoOrientation = .portrait
        cameraPreviewView.layer.addSublayer(previewLayer)
    }
    
    private func startScanning() {
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            self?.captureSession.startRunning()
        }
    }
    
    // MARK: - Actions
    @objc private func backButtonTapped() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc private func flashButtonTapped() {
        guard let device = AVCaptureDevice.default(for: .video) else { return }
        
        do {
            try device.lockForConfiguration()
            
            if device.hasTorch {
                if isFlashOn {
                    device.torchMode = .off
                    flashButton.setImage(UIImage(systemName: "bolt.slash.fill"), for: .normal)
                } else {
                    device.torchMode = .on
                    flashButton.setImage(UIImage(systemName: "bolt.fill"), for: .normal)
                }
                isFlashOn.toggle()
            }
            
            device.unlockForConfiguration()
        } catch {
            print("Flash error: \(error)")
        }
    }
    
    @objc private func captureButtonTapped() {
        guard !isScanning else { return }
        
        isScanning = true
        let photoSettings = AVCapturePhotoSettings()
        stillImageOutput.capturePhoto(with: photoSettings, delegate: self)
    }
    
    @objc private func albumButtonTapped() {
        let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = .photoLibrary
        imagePickerController.delegate = self
        present(imagePickerController, animated: true)
    }
    
    @objc private func saveButtonTapped() {
        guard let image = restoredImage ?? originalImage else { return }
        
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    @objc private func shareButtonTapped() {
        guard let image = restoredImage ?? originalImage else { return }
        
        let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
        present(activityViewController, animated: true)
    }
    
    @objc private func restoreButtonTapped() {
        guard let image = originalImage, !isRestoring else { return }
        
        isRestoring = true
        restoreButton.setTitle("修复中...", for: .normal)
        restoreButton.isEnabled = false
        
        // 开始AI修复
        startPhotoRestoration(image: image)
    }
    
    @objc private func retakeButtonTapped() {
        originalImage = nil
        restoredImage = nil
        isRestoring = false
        resultView.isHidden = true
        overlayView.isHidden = false
        scanFrameView.isHidden = false
        bottomView.isHidden = false
        
        for cornerView in cornerViews {
            cornerView.isHidden = false
        }
        
        startScanning()
    }
    
    @objc private func themeDidChange() {
        // 相机页面不需要主题切换，保持黑色背景
    }
    
    // MARK: - Photo Restoration
    private func startPhotoRestoration(image: UIImage) {
        SVProgressHUD.show(withStatus: "正在修复照片...")
        
        // 模拟AI修复过程（实际项目中这里会调用真实的AI修复API）
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { [weak self] in
            self?.handleRestorationSuccess(image: image)
        }
    }
    
    private func handleRestorationSuccess(image: UIImage) {
        isRestoring = false
        SVProgressHUD.dismiss()
        
        // 模拟修复后的图片（实际项目中这里会是AI修复的结果）
        restoredImage = image
        
        // 保存到历史记录
        if let originalImage = originalImage, let restoredImage = restoredImage {
            HistoryRecordManager.shared.addPhotoRestorationRecord(
                originalImage: originalImage,
                restoredImage: restoredImage
            )
        }
        
        // 显示修复结果
        showRestorationResult()
    }
    
    private func showRestorationResult() {
        // 显示修复后的图片
        restoredImageView.image = restoredImage
        restoredImageView.isHidden = false
        
        // 更新按钮状态
        restoreButton.setTitle("重新修复", for: .normal)
        restoreButton.isEnabled = true
        
        SVProgressHUD.showSuccess(withStatus: "修复完成")
    }
    
    private func showResultView() {
        // 隐藏扫描界面，显示结果界面
        overlayView.isHidden = true
        scanFrameView.isHidden = true
        bottomView.isHidden = true
        resultView.isHidden = false
        
        for cornerView in cornerViews {
            cornerView.isHidden = true
        }
        
        captureSession.stopRunning()
    }
    
    // MARK: - Helper Methods
    private func showAlert(title: String, message: String, completion: ((UIAlertAction) -> Void)? = nil) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: completion))
        present(alert, animated: true)
    }
    
    @objc private func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            SVProgressHUD.showError(withStatus: "保存失败: \(error.localizedDescription)")
        } else {
            SVProgressHUD.showSuccess(withStatus: "已保存到相册")
        }
    }
}

// MARK: - AVCapturePhotoCaptureDelegate
extension PhotoRestorationViewController: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        isScanning = false
        
        if let error = error {
            showAlert(title: "拍照失败", message: error.localizedDescription)
            return
        }
        
        guard let imageData = photo.fileDataRepresentation(),
              let image = UIImage(data: imageData) else {
            showAlert(title: "拍照失败", message: "无法获取图片数据")
            return
        }
        
        originalImage = image
        originalImageView.image = image
        
        // 显示结果界面
        showResultView()
    }
}

// MARK: - UIImagePickerControllerDelegate
extension PhotoRestorationViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true) {
            if let image = info[.originalImage] as? UIImage {
                self.originalImage = image
                self.originalImageView.image = image
                
                // 显示结果界面
                self.showResultView()
            }
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
} 